﻿#include <QEventLoop>
#include "CVideoWorkMange.h"
#include "Public.h"
#include "CGlobal.h"
#include "CSqlOper.h"

CVideoWorkMange::CVideoWorkMange(CCamerCtrMange* pCamerCtrMange, CDevDataCam* pDevData)
	: m_pCamerCtrMange(pCamerCtrMange),m_pDevData(pDevData)
{
	m_pMutex = new QMutex(QMutex::Recursive);
	m_bhread.store(false);
	m_bShouldStop = false;
	m_bFrist = true;
	m_bQueryFrist = true;
	m_nLoginCount = 10;
}

CVideoWorkMange::~CVideoWorkMange()
{
	// 先设置停止标志
	m_bShouldStop = true;

	// 等待线程安全退出
	quit();
	wait(2000); // 设置超时时间

	// 如果线程还在运行，强制终止
	if (isRunning())
	{
		terminate();
		wait(1000);
	}

	if (m_pMutex != nullptr)
	{
		delete m_pMutex;
		m_pMutex = nullptr;
	}
}

void CVideoWorkMange::threadStart()
{
	QMutexLocker locker(m_pMutex);
	if (!m_bhread.load())
	{
		if (m_bFrist)
		{
			start();
			m_bFrist = false;
		}
		m_bhread.store(true);
	}
}

void CVideoWorkMange::threadStop()
{
	QMutexLocker locker(m_pMutex);
	if (m_bhread.load())
	{
		m_bhread.store(false);
	}
}

void CVideoWorkMange::queryAlarm()
{
	if (m_pDevData == nullptr)
	{
		return;
	}
	m_pDevData->m_pMutex->lock();
	m_pDevData->m_vecAlarm.clear();
	m_pDevData->m_vecAlarm.squeeze();
	m_pDevData->m_pMutex->unlock();
	QString sErrMsg = "";
	QVector<QSqlRecord> vecRecord;
	bool bRet=CSqlOper::instance().selectQuertAlarmRecord(m_pDevData->m_sDevGuid, vecRecord,sErrMsg);
	if (bRet)
	{
		m_pDevData->m_pMutex->lock();
		for (int i = 0; i < vecRecord.size(); i++)
		{
			AlarmItem item;
			item.sGuid=vecRecord[i].value("GUID").toString().trimmed();
			item.sCamerName = vecRecord[i].value("DEV_NAME").toString().trimmed();
			item.sAlarmType = vecRecord[i].value("EVENT_TYPE").toString().trimmed();
			item.sAlarmTime = vecRecord[i].value("ALARM_TIME").toDateTime().toString("yyyy/MM/dd hh:mm:ss");
			item.nAlarmLevel = vecRecord[i].value("ALARM_LEVEL").toInt();
			item.nIsConfirm = vecRecord[i].value("IS_CONFIRM").toInt();
			item.sUrl = vecRecord[i].value("IMG_URL").toString().trimmed();
			m_pDevData->m_vecAlarm.push_back(item);
		}
		m_pDevData->m_pMutex->unlock();
	}
}

void CVideoWorkMange::judgmentState()
{
	if (m_pDevData == nullptr)
	{
		return;
	}
	m_pDevData->m_pMutex->lock();
	QVector<AlarmItem> vecItem = m_pDevData->m_vecAlarm;
	m_pDevData->m_pMutex->unlock();
	QMap<QString, QVector<AlarmItem>> mapAlarm;
	for (int i = 0; i < vecItem.size(); i++)
	{
		if (mapAlarm.contains(vecItem[i].sAlarmType))
		{
			mapAlarm[vecItem[i].sAlarmType].push_back(vecItem[i]);
		}
		else
		{
			QVector<AlarmItem> vecAlarmItem;
			vecAlarmItem.push_back(vecItem[i]);
			mapAlarm[vecItem[i].sAlarmType] = vecAlarmItem;
		}
	}
	bool bCoalFlow=true;						//煤流量
	bool bBeltForeign = true;					//皮带异物
	bool bLargeCoal = true;						//大块煤
	bool bBeltDeviation = true;					//皮带跑偏
	bool bSafetyHelmet = true;					//安全帽反光衣
	bool bSmokeFire = true;						//烟雾火点
	bool bSmokeMakeCall = true;					//抽烟打电话
	bool bTemp = true;							//测温报警
	bool bPerimeter = true;						//周界防范报警
	bool bBlock = true;							//传送带堵料
	bool bThrow = true;							//抛洒滴漏
	bool bStreet = true;						//街面行为

	QString sCoalFlowUrl = "";						//煤流量图片Url
	QString sBeltForeignUrl = "";					//皮带异物Url
	QString sLargeCoalUrl = "";						//大块煤Url
	QString sBeltDeviationUrl = "";					//皮带跑偏Url
	QString sSafetyHelmetUrl = "";					//安全帽反光衣Url
	QString sSmokeFireUrl = "";						//烟雾火点Url
	QString sSmokeMakeCallUrl = "";					//抽烟打电话Url
	QString sTempUrl = "";							//测温报警Url
	QString sPerimeterUrl = "";						//周界防范报警Url
	QString sBlockUrl = "";							//传送带堵料Url
	QString sThrowUrl = "";							//抛洒滴漏Url
	QString sStreetUrl = "";						//街面行为Url

	for (auto itor = mapAlarm.begin(); itor != mapAlarm.end(); itor++)
	{
		QVector<AlarmItem> vecAlarmItem = itor.value();
		QString sAlarmType = itor.key();
		//寻找是否存在一段时间内报警且未确认的记录
		bool bFind = false;
		QString sUrl = "";
		for (int i = 0; i < vecAlarmItem.size(); i++)
		{
			if (qAbs(QDateTime::fromString(vecAlarmItem[i].sAlarmTime, "yyyy/MM/dd hh:mm:ss").secsTo(QDateTime::currentDateTime())) < g_nAlarmTime)
			{
				if (vecAlarmItem[i].nIsConfirm == 0)
				{
					bFind = true;
					sUrl = vecAlarmItem[i].sUrl;
					break;
				}
			}
		}
		if (bFind)
		{
			if (sAlarmType == A2T("堆煤煤流占比"))
			{
				bCoalFlow = false;
				sCoalFlowUrl = sUrl;
			}
			else if (sAlarmType == A2T("皮带异物"))
			{
				bBeltForeign = false;
				sBeltForeignUrl = sUrl;
			}
			else if (sAlarmType == A2T("大块煤检测"))
			{
				bLargeCoal = false;
				sLargeCoalUrl = sUrl;
			}
			else if (sAlarmType == A2T("皮带跑偏算法"))
			{
				bBeltDeviation = false;
				sBeltDeviationUrl = sUrl;
			}
			else if (sAlarmType == A2T("烟雾火点"))
			{
				bSmokeFire = false;
				sSmokeFireUrl = sUrl;
			}
			else if (sAlarmType == A2T("安全帽反光衣"))
			{
				bSafetyHelmet = false;
				sSafetyHelmetUrl = sUrl;
			}
			else if (sAlarmType == A2T("抽烟打电话"))
			{
				bSmokeMakeCall = false;
				sSmokeMakeCallUrl = sUrl;
			}
			else if (sAlarmType == A2T("测温报警"))
			{
				bTemp = false;
				sTempUrl = sUrl;
			}
			else if (sAlarmType == A2T("周界防范"))
			{
				bPerimeter = false;
				sPerimeterUrl = sUrl;
			}
			else if (sAlarmType == A2T("传送带堵料"))
			{
				bBlock = false;
				sBlockUrl = sUrl;
			}
			else if (sAlarmType == A2T("抛洒滴漏"))
			{
				bThrow = false;
				sThrowUrl = sUrl;
			}
			else if (sAlarmType == A2T("街面行为"))
			{
				bStreet = false;
				sStreetUrl = sUrl;
			}
		}
	}

	if (m_pDevData == nullptr)
		return;
	m_pDevData->m_pMutex->lock();
	m_pDevData->m_bBeltDeviation = bBeltDeviation;
	m_pDevData->m_bBeltForeign = bBeltForeign;
	m_pDevData->m_bCoalFlow = bCoalFlow;
	m_pDevData->m_bLargeCoal = bLargeCoal;
	m_pDevData->m_bSmokeFire = bSmokeFire;
	m_pDevData->m_bSafetyHelmet = bSafetyHelmet;
	m_pDevData->m_bSmokeMakeCall = bSmokeMakeCall;
	m_pDevData->m_bTemp = bTemp;
	m_pDevData->m_bPerimeter = bPerimeter;
	m_pDevData->m_bBlock = bBlock;
	m_pDevData->m_bThrow = bThrow;
	m_pDevData->m_bStreet = bStreet;
	m_pDevData->m_mapDevPoint[enVideoState]->setValue(m_pDevData->m_bLoginValue);
	m_pDevData->m_mapDevPoint[enCoalFlowState]->setValue(m_pDevData->m_bCoalFlow,sCoalFlowUrl);
	m_pDevData->m_mapDevPoint[enBeltForeignState]->setValue(m_pDevData->m_bBeltForeign,sBeltForeignUrl);
	m_pDevData->m_mapDevPoint[enLargeCoalState]->setValue(m_pDevData->m_bLargeCoal,sLargeCoalUrl);
	m_pDevData->m_mapDevPoint[enBeltDeviationState]->setValue(m_pDevData->m_bBeltDeviation,sBeltDeviationUrl);
	m_pDevData->m_mapDevPoint[enSmokeFireState]->setValue(m_pDevData->m_bSmokeFire,sSmokeFireUrl);
	m_pDevData->m_mapDevPoint[enSafetyHelmetState]->setValue(m_pDevData->m_bSafetyHelmet,sSafetyHelmetUrl);
	m_pDevData->m_mapDevPoint[enSmokeMakeCallState]->setValue(m_pDevData->m_bSmokeMakeCall,sSmokeMakeCallUrl);
	m_pDevData->m_mapDevPoint[enTempState]->setValue(m_pDevData->m_bTemp,sTempUrl);
	m_pDevData->m_mapDevPoint[enPerimeterState]->setValue(m_pDevData->m_bPerimeter,sPerimeterUrl);
	m_pDevData->m_mapDevPoint[enBlockState]->setValue(m_pDevData->m_bBlock,sBlockUrl);
	m_pDevData->m_mapDevPoint[enThrowState]->setValue(m_pDevData->m_bThrow,sThrowUrl);
	m_pDevData->m_mapDevPoint[enStreetState]->setValue(m_pDevData->m_bStreet,sStreetUrl);
	if (m_pDevData->m_bBeltRun)
	{
		if (qAbs(m_pDevData->m_dBeltRun.secsTo(QDateTime::currentDateTime())) < g_nAlarmTime)
		{
			m_pDevData->m_mapDevPoint[enBeltRunState]->setValue(true);
		}
		else
		{
			m_pDevData->m_mapDevPoint[enBeltRunState]->setValue(false);
			m_pDevData->m_bBeltRun = false;
		}
	}
	else
	{
		m_pDevData->m_mapDevPoint[enBeltRunState]->setValue(false);
	}
	m_pDevData->m_pMutex->unlock();
}

void CVideoWorkMange::run()
{
	while (!m_bShouldStop)
	{
		QMutexLocker locker(m_pMutex); // 使用QMutexLocker自动管理锁

		if (!m_bhread.load())
		{
			sysSleep(10);
			continue;
		}

		// 在每次访问前检查指针是否有效
		if (!m_pDevData || m_bShouldStop)
		{
			break;
		}

		if (m_nLoginCount == 10)
		{
			if (m_pDevData->m_bLogin == false)
			{
				SCtrInfo infoTx;
				infoTx.m_sGuid = m_pDevData->m_sDevGuid;
				infoTx.m_nCtrCmd = enCLogin;
				infoTx.m_nCtrDevType = enSubDev1;
				infoTx.m_nSubCtrDevType = enCamer;
				infoTx.m_bCtrSync = false;
				bool bTxRet = m_pCamerCtrMange->CtrDevice(infoTx);
			}
			m_nLoginCount = 0;
		}
		else
		{
			m_nLoginCount++;
		}

		// 检查是否需要停止
		if (m_bShouldStop) 
		{
			break;
		}

		//一段时间后查询数据库
		if (m_bQueryFrist || qAbs(m_dLastTime.secsTo(QDateTime::currentDateTime())) > 10)
		{
			queryAlarm();
			m_dLastTime = QDateTime::currentDateTime();
		}
		judgmentState();
		m_bQueryFrist = false;

		QEventLoop loop;
		QTimer::singleShot(1000, &loop, SLOT(quit()));//一秒钟查询一下数据库
		loop.exec();
		// 再次检查
		if (m_bShouldStop) 
		{
			break;
		}
	}
}
